package ltd.newbee.mall.config.handler;

import cn.hutool.core.util.StrUtil;
import ltd.newbee.mall.common.NewBeeMallException;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.config.TokenAdminUser;
import ltd.newbee.mall.config.annotation.IgnoreAuth;
import ltd.newbee.mall.dao.NewBeeAdminUserTokenMapper;
import ltd.newbee.mall.entity.AdminUserToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/****
 * 重写认证拦截器
 */
@Component
@Order(99999)
public class AuthInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthInterceptor.class);

    @Resource
    private TokenAdminUser tokenAdminUser;

    @Resource
    private NewBeeAdminUserTokenMapper newBeeAdminUserTokenMapper;

    /**
     * 认证登录用户token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("===开始拦截===");
        if (handler instanceof HandlerMethod) {
            long startTime = System.currentTimeMillis();
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            IgnoreAuth authority = handlerMethod.getMethodAnnotation(IgnoreAuth.class);
            if (authority != null) {
                // 忽略认证
                return true;
            }
            String tokenValue = request.getHeader(tokenAdminUser.getHeader());
            LOGGER.info("拦截当前 token = {}", tokenValue);
            if (StrUtil.isEmpty(tokenValue)) {
                NewBeeMallException.fail(ServiceResultEnum.NOT_LOGIN_ERROR.getResult());
                return false;
            }
            AdminUserToken userToken = newBeeAdminUserTokenMapper.selectByToken(tokenValue);
            if (ObjectUtils.isEmpty(userToken)) {
                NewBeeMallException.fail(ServiceResultEnum.NOT_LOGIN_ERROR.getResult());
                return false;
            }
            if (userToken.getExpireTime().getTime() < startTime) {
                // 删除令牌
                newBeeAdminUserTokenMapper.deleteByPrimaryKey(userToken.getAdminUserId());
                NewBeeMallException.fail(ServiceResultEnum.ADMIN_TOKEN_EXPIRE_ERROR.getResult());
                return false;
            }
            // 分钟单位
            long unit = 1000 * 1000L;
            if (userToken.getExpireTime().getTime() < startTime + tokenAdminUser.getInterval() * unit) {
                // 更新令牌延时
                AdminUserToken adminUserToken = new AdminUserToken();
                adminUserToken.setAdminUserId(userToken.getAdminUserId());
                adminUserToken.setToken(tokenValue);
                adminUserToken.setUpdateTime(new Date(startTime));
                adminUserToken.setExpireTime(new Date(startTime + tokenAdminUser.getRefresh() * unit));
                newBeeAdminUserTokenMapper.updateByPrimaryKeySelective(adminUserToken);
            }
        }
        return true;
    }
}
